package com.sample.xcrash;

import com.sample.xcrash_lib.ICrashCallback;
import com.sample.xcrash_lib.TombstoneManager;
import com.sample.xcrash_lib.TombstoneParser;
import com.sample.xcrash_lib.XCrash;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.delegation.AbilityDelegatorRegistry;
import ohos.app.Context;
import ohos.utils.zson.ZSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Init {

    public final Ability currentTopAbility = AbilityDelegatorRegistry.getAbilityDelegator().getCurrentTopAbility();
    public final Context mContext = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext();

    public int xcrash_Init;
    // InitParameters
    public int xcrash_InitParameters;

    public void setUp() throws Exception {

        // callback for java crash, native crash and ANR
        ICrashCallback callback = new ICrashCallback() {
            @Override
            public void onCrash(String logPath, String emergency) throws Exception {

                if (emergency != null) {
                    debug(logPath, emergency);
                } else {
                    // Add some expanded sections. Send crash report at the next time APP startup.
                    // OK
                    TombstoneManager.appendSection(logPath, "expanded_key_1", "expanded_content");
                    TombstoneManager.appendSection(logPath, "expanded_key_2", "expanded_content_row_1\nexpanded_content_row_2");
                    // Invalid. (Do NOT include multiple consecutive newline characters ("\n\n") in the content string.)
                    TombstoneManager.appendSection(logPath, "expanded_key_3", "expanded_content_row_1\n\nexpanded_content_row_2");

                    debug(logPath, null);
                }
            }
        };

        // Initialize xCrash.
        xcrash_Init = XCrash.init(mContext, new XCrash.InitParameters()
                .setAppVersion("1.2.3-beta456-patch789")
                .setJavaRethrow(true)
                .setJavaLogCountMax(10)
                .setJavaDumpAllThreadsWhiteList(new String[]{"^main$", "^Binder:.*", ".*Finalizer.*"})
                .setJavaDumpAllThreadsCountMax(10)
                .setJavaCallback(callback)
                .setNativeRethrow(true)
                .setNativeLogCountMax(10)
                .setNativeDumpAllThreadsWhiteList(new String[]{"^xcrash\\.sample$", "^Signal Catcher$", "^Jit thread pool$", ".*(R|r)ender.*", ".*Chrome.*"})
                .setNativeDumpAllThreadsCountMax(10)
                .setNativeCallback(callback)
                .setAnrRethrow(true)
                .setAnrLogCountMax(10)
                .setAnrCallback(callback)
                .setPlaceholderCountMax(3)
                .setPlaceholderSizeKb(512)
                .setLogDir(currentTopAbility.getExternalFilesDir("xcrash").toString())
                .setLogFileMaintainDelayMs(1000));


        // Send all pending crash log files.
        new Thread(new Runnable() {
            @Override
            public void run() {

                for (File file : TombstoneManager.getAllTombstones()) {
                    try {
                        sendThenDeleteCrashLog(file.getCanonicalPath(), null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    private void sendThenDeleteCrashLog(String logPath, String emergency) {
        // Parse
        //Map<String, String> map = TombstoneParser.parse(logPath, emergency);
        //String crashReport = new JSONObject(map).toString();

        // Send the crash report to server-side.
        // ......

        // If the server-side receives successfully, delete the log file.
        //
        // Note: When you use the placeholder file feature,
        //       please always use this method to delete tombstone files.
        //
        //TombstoneManager.deleteTombstone(logPath);
    }

    private void debug(String logPath, String emergency) {

        // Parse and save the crash info to a JSON file for debugging.
        FileWriter writer = null;
        try {
            File debug = new File(XCrash.getLogDir() + "/debug.json");
            debug.createNewFile();
            writer = new FileWriter(debug, false);
            writer.write(ZSONObject.toZSONString(TombstoneParser.parse(logPath, emergency)));
        } catch (Exception e) {

        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

}
